package com.example.duihua.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class WebSocketServer {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketServer.class);

    private final ServerBootstrap serverBootstrap;
    private final int port;
    private Channel serverChannel;

    public WebSocketServer(ServerBootstrap serverBootstrap, int port) {
        this.serverBootstrap = serverBootstrap;
        this.port = port;
    }

    @PostConstruct
    public void start() throws Exception {
        try {
            serverChannel = serverBootstrap.bind("0.0.0.0", port).sync().channel();
            logger.info("WebSocket服务器启动成功，监听端口: {}", port);
        } catch (Exception e) {
            logger.error("WebSocket服务器启动失败", e);
            throw e;
        }
    }

    @PreDestroy
    public void stop() {
        if (serverChannel != null) {
            serverChannel.close();
            logger.info("WebSocket服务器已关闭");
        }
    }
}